package com.mk.cloud.common.service.core;

import act.apidoc.Description;
import act.app.App;
import act.event.OnEvent;
import act.ws.WebSocketCloseEvent;
import act.ws.WebSocketConnectEvent;
import act.ws.WebSocketConnectionManager;
import act.ws.WebSocketContext;
import com.mk.cloud.common.domain.CpMsg;
import org.osgl.mvc.annotation.WsAction;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class WsService{
    private static final Map<String,String> sessionMap = new HashMap<>();

    private static final AtomicInteger CONN_COUNTER = new AtomicInteger(0);
    @WsAction("/ws/msg")
    @Description("用来将客户端的socket请求注册到tag别名，方便推送")
    public void onMessage(CpMsg message, WebSocketContext context) throws Exception {
        context.tag(context.actionContext().paramVal("userid"));
    }

    @OnEvent
    @Description("socket连接建立时触发的事件")
    public static void handleConnection(WebSocketConnectEvent event) {
        CONN_COUNTER.incrementAndGet();
        final WebSocketContext context = event.source();
    }

    @OnEvent
    @Description("任何 websocket 连接断开时候触发的事件")
    public static void handleConnectionClose(WebSocketCloseEvent event) {
        final WebSocketContext context = event.source();
        CONN_COUNTER.decrementAndGet();
//        System.out.println(context.closed());
//        context.close();
    }


//    @OnEvent
    @Description("服务端向客户端发送消息")
    public static void handleNewsUpdate(CpMsg message) {
        WebSocketConnectionManager connectionManager = App.instance().getInstance(WebSocketConnectionManager.class);
        connectionManager.sendJsonToTagged(message,message.getUserid());
    }

}
